package cc;


import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;

public class HttpRequest {

    //单线程视频下载
    public static String sendGet2(String url, String filePath) {
        String result = "done";
        BufferedReader in = null;
        try {
            System.out.println(new SimpleDateFormat("yy-MM-dd HH:mm:ss").format(new Date()) + "  HttpRequest.sendGet=>> " + url);
            String urlNameString = url;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            connection.setRequestProperty("User-Agent",
                    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36");
            // 建立实际的连接
            connection.connect();
          /*  // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (Map.Entry<String, List<String>> entry : map.entrySet()) {
                System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());

            }*/
            InputStream inputStream = connection.getInputStream();

            byte[] getData = readInputStream(inputStream);

            java.io.File saveDir = new java.io.File("D:/tmp");
            if (!saveDir.exists()) {
                saveDir.mkdir();
            }
            java.io.File file = new java.io.File(filePath);
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(getData);
            if (fos != null) {
                fos.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            result = "fail";
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    public static byte[] readInputStream(InputStream inputStream)
            throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }

    public static void main(String[] args) {
        String sr = HttpRequest.sendGet2("http://www.yjizz8.com/file/11150/1/94b46a2f95df6e2a6302/1515040134/mp4/11150.mp4", "");
    }
}
